package cn.toleo.search.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.alibaba.dubbo.rpc.Result;
import cn.toleo.common.pojo.SearchItem;
import cn.toleo.common.pojo.SearchResult;


/**
 * 查询索引库商品dao
 * @author Administrator
 *
 */

@Repository
public class SearchDao {
	@Autowired
	private SolrServer solrServer;
	
	public SearchResult search(SolrQuery query) throws Exception{
		//三步sorlDocument
		QueryResponse response = solrServer.query(query);
		SolrDocumentList solrDocumentList = response.getResults();
		
		//一步结果 输入参数
		List<SearchItem> itemList = new ArrayList<>();
		
		//附属
		SearchResult result = new SearchResult();
		long numFound = solrDocumentList.getNumFound();
		result.setRecordCount(numFound);
		
		for(SolrDocument solrDocument:solrDocumentList){
			SearchItem item = new SearchItem();
			item.setCategory_name((String)solrDocument.get("item_categoty_name"));
			item.setId((String)solrDocument.get("id"));
			//取第一张图片
			String image=(String)solrDocument.get("item_image");
			if(StringUtils.isNoneBlank(image)){
				image=image.split(",")[0];
			}
			item.setImage(image);
			item.setPrice((Long)solrDocument.get("item_price"));
			item.setSell_point((String)solrDocument.get("item_sell_point"));
			//取高亮显示
			Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
			List<String> list = highlighting.get(solrDocument.get("id")).get("item_title");
			String title="";
			if(list!=null&&list.size()>0){
				title=list.get(0);
						
			}else{
				title=(String)solrDocument.get("item_title");
			}
			item.setTitle(title);
			itemList.add(item);
		}
		//把结果添加到SearchReasult中
		result.setItemList(itemList);
		return result;

	}
}
